import { TextField, InputAdornment, Popper, Paper, ClickAwayListener } from '@mui/material'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ArrowDropDown } from '@mui/icons-material';
import { makeStyles } from 'tss-react/mui';
import MyTreeViewLazy from '../../MyTreeViewLazy';
import api from '../../../api';
import { translateTree, searchDataById } from '../../../utils/util'
import { useLocation } from 'react-router';

const useStyles = makeStyles()(() => ({
  spreaderSelectTree: {
    '.MuiInputBase-root': {
      cursor: 'pointer'
    },
    '.MuiInputBase-input': {
      cursor: 'pointer'
    }
  }
}))

const SpreaderSelectTree = (props) => {
  const location = useLocation()
  const { classes } = useStyles()
  const { t, i18n: { language } } = useTranslation()
  const { getCurrentSpreaderId } = props
  const inputRef = useRef(null)
  const [popWidth, setPopWidth] = useState(0)
  const [anchorEl, setAnchorEl] = useState(null)
  const [treeData, setTreeData] = useState([])
  const [defaultClickNodeKeys, setDefaultClickNodeKeys] = useState([])
  const [spreaderId, setSpreaderId] = useState('')

  const open = Boolean(anchorEl)

  const findFirstDomByType = useCallback((treeData, type, result) => {
    if (treeData?.length) {
      for(let i = 0; i < treeData.length; i++) {
        if (result?.id && result.type === type) {
          break
        }
        if (treeData[i].id && treeData[i].type === type) {
          result = treeData[i]
          break
        } else if (treeData[i].children?.length) {
          result = findFirstDomByType(treeData[i].children, type, result)
        }
      }
    }
    return result
  }, [])

  const initialTreeRoot = useCallback(async () => {
    try {
      const res = await api.spreader.queryZone({ parentId: '' })
      if (res?.data?.length) {
        const roots = res.data.map(item => ({
          ...item,
          name: item.i18nName,
          disabledItem: true,
          type: 'zone'
        }))
        let filterRoot = null
        if (location.state?.treeDefaultRootId) {
          const defaultRootIndex = roots.findIndex(item => item.id === location.state.treeDefaultRootId)
          if (defaultRootIndex >= 0) {
            filterRoot = roots[defaultRootIndex]
          } else {
            filterRoot = roots[0]
          }
        } else {
          filterRoot = roots[0]
        }
        const firstNodeChildren = await queryTreeByRoot(filterRoot)
        filterRoot.children = firstNodeChildren?.length ? firstNodeChildren : undefined
        filterRoot.isLeaf = firstNodeChildren?.length ? false : true
        if (location.state?.treeDefaultAssetId) {
          setDefaultClickNodeKeys([location.state.treeDefaultAssetId])
          setSpreaderId(location.state.treeDefaultAssetId)
          if (getCurrentSpreaderId && typeof (getCurrentSpreaderId) === 'function') {
            getCurrentSpreaderId(location.state.treeDefaultAssetId)
          }
        } else {
          const firstSpreader = findFirstDomByType(roots, 'spreader', {})
          if (firstSpreader?.id) {
            setDefaultClickNodeKeys([firstSpreader.id])
            setSpreaderId(firstSpreader.id)
            if (getCurrentSpreaderId && typeof (getCurrentSpreaderId) === 'function') {
              getCurrentSpreaderId(firstSpreader.id)
            }
          }
        }
        setTreeData(roots)
      }
    } catch (err) {
      console.log(err)
    }
  }, [])

  useEffect(() => {
    setPopWidth(inputRef.current.clientWidth)
    initialTreeRoot()
  }, [])

  const controlPopper = useCallback(() => {
    if (!anchorEl) {
      setAnchorEl(inputRef.current)
    } else {
      setAnchorEl(null)
    }
  }, [anchorEl])

  const handleClose = useCallback(() => {
    setAnchorEl(null)
  }, [])

  const queryTreeByRoot = useCallback(async (nodeData, resolve, reject) => {
    try {
      const res = await api.spreader.getZoneTree({ parentId: nodeData.id })
      if (res?.data) {
        const { childZones, ports, spreaders } = res.data
        const treeData = translateTree(childZones, ports, spreaders, 'spreader')
        if (treeData?.length) {
          resolve && resolve(treeData)
          return Promise.resolve(treeData)
        }
      }
      resolve && resolve(null)
      return Promise.resolve(null)
    } catch (err) {
      reject && reject(err)
      return Promise.reject(err)
    }
  }, [])

  const onNodeSelect = useCallback((_, key, nodeData) => {
    if (nodeData.id !== spreaderId) {
      setSpreaderId(nodeData.id)
      if (getCurrentSpreaderId && typeof (getCurrentSpreaderId) === 'function') {
        getCurrentSpreaderId(nodeData.id)
      }
    }
  }, [spreaderId])

  const getInputShowValue = useCallback(() => {
    if (!spreaderId) {
      return ''
    }
    const nodeData = searchDataById(spreaderId, treeData)
    if (nodeData?.name) {
      return nodeData.name.i18nValue[language] ? nodeData.name.i18nValue[language] : nodeData.name.defaultValue
    }
    return ''
  }, [spreaderId, language, treeData])

  return (
    <ClickAwayListener onClickAway={handleClose}>
      <div className={`width-full ${classes.spreaderSelectTree}`} ref={inputRef}>
        <TextField
          onClick={controlPopper}
          value={getInputShowValue()}
          label={t('common.device')}
          variant="filled"
          InputProps={{
            readOnly: true,
            endAdornment: <InputAdornment position="end"><ArrowDropDown/></InputAdornment>,
          }}
        />
        <Popper
          // Note: The following zIndex style is specifically for documentation purposes and may not be necessary in your application.
          sx={{ zIndex: 1200, width: popWidth }}
          open={open}
          anchorEl={anchorEl}
          placement='bottom'
          keepMounted
        >
          <Paper className='width-full overFlowAuto pd16' sx={{ maxHeight: 500 }}>
            <MyTreeViewLazy
              lazy
              cancelByClick={false}
              changeExpandOnLabel
              proprtyRead={{
                nodeId: 'id',
                childrenpropety: 'children',
                labelpropety: 'name',
                isLeaf: 'isLeaf'
              }}
              treeData={treeData}
              loadDataByNode={queryTreeByRoot}
              defaultClickNodeKeys={defaultClickNodeKeys}
              onNodeSelect={onNodeSelect}
            />
          </Paper>
        </Popper>
      </div>
    </ClickAwayListener>
  )
}

export default SpreaderSelectTree